﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.ModelBinding;
using Newtonsoft.Json.Linq;

namespace Cofe.Web.Utils
{
    public static class MediaFormatterUtils
    {
        public static bool CanFormatAsJObject(HttpContent content)
        {
            //To-Do: Check request is json.

            //Check MediaFormatter Exists
            if (!(CofeWsServices.GetMediaFormatter().Any(f => f is JQueryMvcFormUrlEncodedFormatter)))
                return false;

            return true;
        }

        public static async Task<JObject> FormatAsJObjectAsync(HttpContent content)
        {
            var fmter = CofeWsServices.GetMediaFormatter().First((f) => f is JQueryMvcFormUrlEncodedFormatter);
            try
            {
                var result = await fmter.ReadFromStreamAsync(typeof(JObject),
                     await content.ReadAsStreamAsync(),
                    content, null);
                Debug.WriteLine(result);

                return (JObject)result;
            }
            catch (Exception ex)
            {
                throw new FormatException("Format to JObject failed", ex);
            }

        }

    }
}